package com.lbn.monitor.util;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

public class AppUtils {

    public static PackageInfo getPackageInfo(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            return pi;
        } catch (PackageManager.NameNotFoundException e) {
        }
        return null;
    }

    public static ApplicationInfo getApplicationInfo(Context context, int flag) {
        try {
            PackageManager pm = context.getPackageManager();
            return pm.getApplicationInfo(context.getPackageName(), flag);
        } catch (PackageManager.NameNotFoundException e) {
        }
        return null;
    }

    public static int getVersionCode(Context context) {
        try {
            return getPackageInfo(context).versionCode;
        } catch (NullPointerException e) {
            return -1;
        }
    }

    private static String versionName;

    public static String getVerionName(Context context) {

        if(versionName!=null){
            return versionName;
        }

        try {
            versionName = getPackageInfo(context).versionName;
            return versionName;
        } catch (NullPointerException e) {
            return "unknow";
        }
    }

    private static String metaString;

    public static String getMetaString(Context context, String name) {

        if(metaString!=null){
            return metaString;
        }

        try {
            ApplicationInfo appInfo = getApplicationInfo(context, PackageManager.GET_META_DATA);
            metaString = appInfo.metaData.getString(name);
            return metaString;
        } catch (NullPointerException e) {
            return "unknown";
        }
    }

}
